/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */
package info.peigen.hotpot.component.open.api.core.service.processor.base;

import cn.hutool.core.util.ObjectUtil;
import info.peigen.hotpot.common.core.result.ResultBase;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessorServiceContext;
import jakarta.validation.ConstraintViolationException;

import java.sql.SQLIntegrityConstraintViolationException;


/**
 * <b>(OpenApiProcessorServiceInvoke)</b>
 * 服务层接口,待具体的服务去实现
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/5/26
 */
public interface OpenApiProcessorServiceInvoke {

    /**
     * 增加预处理处理器
     *
     * @param serviceContext 服务上下文
     */
    default void addPreProcessor(OpenApiProcessorServiceContext serviceContext) {

    }

    /**
     * 增加业务执行处理器
     *
     * @param serviceContext 服务上下文
     */
    void addProcessor(OpenApiProcessorServiceContext serviceContext);

    /**
     * 增加后处理处理器
     *
     * @param serviceContext 服务上下文
     */
    default void addPostProcessor(OpenApiProcessorServiceContext serviceContext) {

    }

    /**
     * 根据不同的情况下，对于异常的处理<br/>
     *
     * @param e              异常
     * @param serviceContext 服务上下文
     */
    default void handleException(Exception e, OpenApiProcessorServiceContext serviceContext) {
        // 初始化一个空的Result
        if (ObjectUtil.isNull(serviceContext.getResult())) {
            serviceContext.setResult(new ResultBase());
        }

        // 入参校验异常
        if (e instanceof ConstraintViolationException || e instanceof IllegalArgumentException) {
            serviceContext.getResult().setFailForParaError(e.getMessage());
            return;
        }

        // 幂等性异常
        if (e instanceof SQLIntegrityConstraintViolationException) {
            serviceContext.getResult().setFail("受到幂等性控制!");
        }

        serviceContext.getResult().setFail(e.getMessage());
    }
}